<template>
  <view>
    <u-navbar :title="title"></u-navbar>

    <view class="goodsList">
      <!-- <checkbox-group> -->
      <view class="list" v-for="(item, idx) in goodsList" :key="idx">
        <view class="goods">
          <u-checkbox v-model="item.check" shape="circle" v-if="item.is_exchange_coin != 1" active-color="#5EBD8A"
            size="40" label-size="28" @change="change(idx)" />
          <image :src="item.goods_data.image" mode="" @click="list_on(idx)"
            :style="{ marginLeft: item.is_exchange_coin == 1 ? '52rpx' : '' }" />
          <view class="info">
            <view class="tit" @click="list_on(idx)">{{ item.goods_data.title }}</view>
            <view class="bi" v-if="item.status == 0 && type == 1" @click="list_on(idx)">
             {{$t('可转换')}} ：<text>{{ item.exchange_integral }}</text>{{$t('幸运币')}}
            </view>
          </view>
        </view>
      </view>
      <view class="" style="height: 100rpx"></view>
      <!-- </checkbox-group> -->
      <u-empty text="暂无数据" mode="list" :show="nullShow" margin-top="400"></u-empty>
    </view>
    <view class="newagain" v-if="isOne == 0 && type == 1">
      {{$t('新人首次转换，额外得重抽卡')}}*1
    </view>
    <view class="newagain" v-if="type == 3 && freight_rule_text != ''">
      {{ freight_rule_text }}
    </view>

    <view class="bottom11 n-flex-row n-justify-between n-align-center">
      <u-checkbox @change="allSelectChange" v-model="allSelect" shape="circle" active-color="#5EBD8A" label-size="28"
        size="40">{{$t('全选')}}</u-checkbox>

      <view class="yixuan" v-if="type == 1">
        <view class="text">
          {{$t('已选')}}{{ xz_count }}{{$t('件')}}|{{$t('合计')}}：<view>{{ xz_jiazhi }}<text>{{$t('幸运币')}}</text></view>
        </view>
      </view>
      <view class="yixuan" v-if="type == 3">
        <view class="text"> {{$t('已选')}}{{ xz_count }}{{$t('件商品')}} </view>
      </view>
      <view class="btns n-flex-row" v-if="type == 1">
        <view class="btn ti" @click="duihuan1">
          {{$t('立即转换')}}
        </view>
      </view>
      <view class="btns n-flex-row" v-if="type == 2">
        <view class="btn ti" @click="zhuanzheng">
          {{$t('立即转增')}}
        </view>
      </view>
      <view class="btns n-flex-row" v-if="type == 3">
        <view class="btn ti" @click="tihuo">
          {{$t('立即提货')}}
        </view>
      </view>
    </view>
    <u-popup v-model="zhuan" mode="center" border-radius="20">
      <view class="zhuan">
        <view class="tit">{{$t('请输入转赠人的手机号')}}</view>
        <u-input v-model="phone" type="number" maxlength="11" :border="true" :placeholder="$t('请输入转赠人注册手机号')" />
        <view class="tip">{{$t('一旦转赠成功不可退货，请谨慎操作')}}</view>
        <view class="btns1">
          <view class="btn11 a" @click="zhuan = false">{{$t('取消')}}</view>
          <view class="btn11 b" @click="zhuanz">{{$t('确定')}}</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      type: 0,
      goodsList: [],
      nullShow: false,
      isOne: "0",
      xz_count: 0,
      xz_jiazhi: 0,
      zhuan: false,
      phone: "", //转赠人手机号
      zhuanId: "",
      id: 0,
      freight_rule_text: "",
      page: 1,
      status: "loadmore",
    };
  },
  onLoad(option) {
    this.goodsList = [];
    this.type = option.type;
    this.id = option.id;
    if (this.type == 1) {
      this.title = this.$t("批量转换");
      uni.$on("qu_pl_huishou", (data) => {
        uni.showLoading({
          title: this.$t('加载中')+"...",
        });
        setTimeout(() => {
          if (this.goodsList.length > 0) {
            var that = this;
            data.ids.forEach(function (item, index) {
              that.change(item);
            });
            uni.hideLoading();
            // console.log("that.goodsList: " + JSON.stringify(that.goodsList));
          }
        }, 500);
      });
    }
    if (this.type == 2) {
      this.title = this.$t("批量转赠");
    }
    if (this.type == 3) {
      this.title = this.$t("批量提货");
    }
  },
  // 触底
  onReachBottom() {
    this.throttle(this.getData(0), 1000);
  },
  onShow() {
	  if (!uni.getStorageSync("user")) {
	      uni.redirectTo({
	      	url:'../../pages/my/login'
	      })
	  }
    this.goodsList = [];
    this.page = 1;
    this.getData(0);
  },
  onUnload() {
    uni.$off("qu_pl_huishou");
  },
  onBackPress() {
      uni.switchTab({
      	url: '/pages/tabBar/cangku'
      });
      return true;  // 阻止返回操作
  },
  //计算属性
  computed: {
    allSelect: {
      set: function (newVal) {
        this.goodsList.forEach((item) => {
          item.check = newVal;
        });
      },
      get: function () {
        return this.goodsList.every((item) => {
          return item.check == true;
        });
      },
    },
  },
  methods: {
    throttle(func, interval) {
      let timeout = null;
      let lastExecTime = 0;
      return function () {
        const context = this;
        const args = arguments;
        const currentTime = Date.now();

        if (currentTime - lastExecTime > interval) {
          clearTimeout(timeout);
          lastExecTime = currentTime;
          func.apply(context, args);
        } else {
          clearTimeout(timeout);
          timeout = setTimeout(function () {
            lastExecTime = currentTime;
            func.apply(context, args);
          }, interval);
        }
      };
    },
    //全选
    allSelectChange() {
      this.allSelect = !this.allSelect;
      let arr = [];
      this.xz_jiazhi = Number(0);
      this.goodsList.forEach((item) => {
        if (item.check == true && item.is_exchange_coin != 1) {
          this.xz_jiazhi = (
            Number(this.xz_jiazhi) + Number(item.exchange_integral)
          ).toFixed(2);
          arr.push(item);
        }
      });
      this.xz_count = arr.length;
    },
    //单选
    change(index) {
      this.goodsList[index].check = !this.goodsList[index].check;
      let arr = [];
      this.xz_jiazhi = Number(0);
      this.goodsList.forEach((item) => {
        if (item.check == true) {
          this.xz_jiazhi = (
            Number(this.xz_jiazhi) + Number(item.exchange_integral)
          ).toFixed(2);
          arr.push(item);
        }
      });
      this.xz_count = arr.length;
    },
    // 单选
    list_on(index) {
      if (item.is_exchange_coin == 1) {
				item.check = false;
				return;
			}
      this.goodsList[index].check = !this.goodsList[index].check;
      let arr = [];
      this.xz_jiazhi = Number(0);
      this.goodsList.forEach((item) => {
        if (item.check == true) {
          this.xz_jiazhi = (
            Number(this.xz_jiazhi) + Number(item.exchange_integral)
          ).toFixed(2);
          arr.push(item);
        }
      });
      this.xz_count = arr.length;
    },
    duihuan1() {
      let arr = [];
      this.goodsList.forEach((item) => {
        if (item.check == true && item.is_exchange_coin != 1) {
          arr.push(item);
        }
      });
      if (arr.length == 0) {
        this.$tip.tip(this.$t("请选择商品"));
        return;
      }
      let data = [];
      arr.forEach((val) => {
        data.push({
          image: val.goods_data.image,
          name: val.goods_data.title,
          price: val.exchange_integral,
          id: val.id,
        });
      });
      uni.setStorageSync("dui", data);
      uni.navigateTo({
        url: "/pages/cangku/duihuan",
      });
      console.log(data);
    },
    zhuanzheng() {
      let arr = [];
      this.goodsList.forEach((item) => {
        if (item.check == true) {
          arr.push(item.id);
        }
      });
      if (arr.length == 1) {
        arr = arr[0];
      } else {
        arr = arr.join();
      }
      console.log(arr);
      this.zhuanId = arr;
      if (arr.length == 0) {
        this.$tip.tip(this.$t("请选择商品"));
        return;
      }
      this.zhuan = true;
    },
    // 确定转赠
    zhuanz() {
      if (!this.$u.test.mobile(this.phone)) {
        this.$tip.tip(this.$t("请输入正确的手机号"));
        return;
      }
      this.$http({
        url: "api/order/prize_give",
        data: {
          id: this.zhuanId,
          receive_username: this.phone,
        },
      })
        .then((res) => {
          console.log(res);
          if (res.data.code == 1) {
            this.zhuan = false;
            this.phone = "";
            this.current = 2;
            this.swiperCurrent = 2;
            this.$tip.tip(res.data.msg);
            setTimeout(() => {
              uni.navigateBack({});
            }, 3000);
          } else {
            this.$tip.tip(res.data.msg);
          }
        })
        .catch((err) => { });
    },
    //提货
    tihuo() {
      let arr = [];
      let th_arr = [];
      this.goodsList.forEach((item) => {
        if (item.check == true) {
          arr.push(item.id);
          var item_arr = {
            image: item.goods_data.image,
            name: item.goods_data.title,
            yunfei:
              item.goods_data.goods_type == 2
                ? 0
                : item.goods_data.freight_value,
            goods_type: item.goods_data.goods_type,
          };
          th_arr.push(item_arr);
        }
      });
      if (arr.length == 1) {
        arr = arr[0];
        var ids = arr;
      } else {
        var ids = arr.join();
      }
      console.log(th_arr);
      if (arr.length == 0) {
        this.$tip.tip(this.$t("请选择提货商品"));
        return;
      }
      uni.setStorageSync("tihuo_data", th_arr);
      uni.navigateTo({
        url: "/pages/cangku/confirmOrder_th?ids=" + ids,
      });
    },
    getData(sta) {
      uni.showLoading({
        title: this.$t("加载中"),
      });
      // this.goodsList = []
      this.$http({
        url: "api/order/get_prize_record",
        data: {
          status: sta,
          page: this.page,
        },
      })
        .then((res) => {
          uni.hideLoading();
          console.log(res, "商品");
          if (res.data.code == 1) {
            this.freight_rule_text = res.data.data.freight_rule_text;
            if (res.data.data.list.length == 0) {
              this.nullShow = true;
            } else if (res.data.data.list.length = 10){
              this.page++;
              this.nullShow = false;
            }
            res.data.data.list.forEach((item) => {
              item.check = false;
            });
            var data = res.data.data.list;
            this.goodsList = this.goodsList.concat(data);
            // this.goodsList = res.data.data.list
            if (this.type == 3) {
              //批量提货的
              this.goodsList.forEach((item) => {
                if (item.id == this.id) {
                  item.check = true;
                  this.xz_count = 1;
                }
              });
            }

            this.isOne = res.data.data.cck;
          } else {
            this.nullShow = true;
            this.$tip.tip(res.data.msg);
          }
        })
        .catch((err) => { });
    },
  },
};
</script>

<style>
@import url("../../static/css/piliang_edit.css");
</style>
